<?php
class Order extends CS_Controller
{
    public function _init()
    {
        $this->load->library('pagination');
        $this->load->library('stream/tourismstream', null, 'tourismstream');
        $this->load->model('region_model', 'region');
        $this->load->model('tourism_delivery_address_model', 'tourism_delivery_address');
        $this->load->model('tourism_order_model', 'tourism_order');
        $this->load->model('tourism_order_main_model', 'tourism_order_main');
        $this->load->model('tourism_cart_goods_model', 'tourism_cart_goods');
        $this->load->model('tourism_order_product_model', 'tourism_order_product');
        $this->load->model('tourism_goods_attr_model', 'tourism_goods_attr');
        $this->load->model('tourism_freight_free_model', 'tourism_freight_free');
        $this->load->model('tourism_freight_template_model', 'tourism_freight_template');
        $this->load->model('tourism_freight_price_list_model', 'tourism_freight_price_list');
        $this->load->model('tourism_order_product_profit_model', 'tourism_order_product_profit');
        $this->load->model('user_account_model','user_account');
        $this->load->model('tourism_goods_category_spec_model','tourism_goods_category_spec');
    }

     /**
     * 确认订单 跳转页面（从购物车跳过来）
     * */
    public function setCartCookie()
    {
        //$cbk 1购物车跳过来 2代表商品详情传过来的
        $goodsAttrId = trim($this->input->post('id'),',');
        $cak = $this->input->post('cbk');
        set_cookie("tid", $goodsAttrId, 86500);
        set_cookie("cbk", $cak, 86500);
        $this->ajaxJson(['status' => true]);
    }

    //商品详情
    public function setGoodsInfoCookie()
    {
        //$cbk 1购物车跳过来 2代表商品详情传过来的
        //$cbk 1购物车跳过来     2代表商品详情传过来的
        $specArray = '';
        $spec_id = $this->input->post('sp');
        if (!empty($spec_id)) {
            $specValue = $this->tourism_goods_category_spec->findBySpec($spec_id);
            if ($specValue->num_rows()>0) {
                $spec = [];
                foreach ($specValue->result() as $item) {
                    $spec[] = $item->attribute_value;
                }
                if (!empty($spec)) {
                    $specArray = join(',', $spec); //选择规格属性
                }
            }
        }
        $goodsAttrId = trim($this->input->post('id'));
        $num = $this->input->post('num') ? $this->input->post('num') : 1;
       
        set_cookie('tid', $goodsAttrId, 86500);
        set_cookie('cbk', 2, 86500);
        set_cookie('num', $num, 86500);
        set_cookie('attr', $specArray,86500); // 属性规格的
        $this->ajaxJson(['status' => true]);
    }

     /**
     * 订单确认页面
     */
    public function confirm()
    {
        $address = $this->tourism_delivery_address->findOne(['uid' => $this->uid]);
        $this->data['allAddress'] = $address;
        $this->load->view('tourism/order/confirm', $this->data);
    }
    
     /**
     * ajax提交刷新订单
     */
    public function ajaxOrderContent()
    {
        $address_id = $this->input->post('address_id');
        if ($address_id) {
            $address = $this->tourism_delivery_address->findOne(['address_id' => $address_id]);
        } else {
            $address = $this->tourism_delivery_address->findOne(['uid' => $this->uid], '*', 'is_default DESC');
        }
        $data['address'] = $address->row();
        $result = $this->unitCost($data['address']);
        if (empty($result)) {
            $this->jsonMessage(site_url('home/ucenter/index'));
        }
        $data['goodsData']   = $result;
        $data['actualBonus'] = $this->user_account->findByUserAccount($this->uid)->row(0)->amount_bonus;// 实际有多少U币
        $data['swim'] = $this->input->post('swim');
        $this->jsonMessage('', $this->load->view('tourism/order/order_content', $data, true));
    }

    //根据cookie--查询数据
    public function getCookieGoods()
    {
        $goodsAttrId =  get_cookie("tid");
        $cak = get_cookie('cbk');
        if (empty($goodsAttrId)) {
            $this->jsonMessage(site_url('home/ucenter/index'));
        }
        if ($cak == 1) {
            $goodsAttrId = explode(',', $goodsAttrId);
            $goodsAttr = $this->tourism_cart_goods->findTourismCartNum($this->uid, $goodsAttrId);
        } else {
            $goodsAttr = $this->tourism_goods_attr->findByGoodsInfo($goodsAttrId);
        }
        if ($goodsAttr->num_rows() < count($goodsAttrId)) {
           $this->jsonMessage(site_url('home/ucenter/index'));
        }
        $result = $goodsAttr->result();
        if ($cak == 2) {
            $num = get_cookie('num');
            $result[0]->goods_num = $num;
            $result[0]->attribute_value = get_cookie('attr');
        }
        return $result;
    }

    /**
     * 确认订单 查询运费模版
     * @param $address
     * @return array|bool
     */
    public function unitCost($address)
    {
        $goodAttr = $this->getCookieGoods();
        if (empty($goodAttr)) {
            return false;
        }
        $orderGoods = array();
        $transportId = array();
        $uid = array();
        foreach ($goodAttr as $value) {
            if ($value->goods_num > $value->number) {
                return false;
            }
            if ($value->transport_id > 0) {
                if (!in_array($value->transport_id, $transportId)) {
                    $transportId[] = $value->transport_id;
                }
                if (!in_array($value->uid, $uid)) {
                    $uid[] = $value->uid;
                }
            }
            $orderGoods[$value->uid]['alias_name']     = $value->alias_name;
            $orderGoods[$value->uid]['uid']            = $value->uid;
            $orderGoods[$value->uid]['user_name']      = $value->user_name ? $value->user_name : $value->mobile_phone;
            $orderGoods[$value->uid]['goodsInfo'][]    = $value;
            $orderGoods[$value->uid]['transport_cost'] = $value->transport_cost;
            $orderGoods[$value->uid]['transport_id']   = $value->transport_id;
        }
        if (!empty($address) && !empty($transportId) && !empty($uid)) {
            //$address = $address->row()->province_name;
            $template = $this->tourism_freight_template->findByTemplate(array('id' => $transportId, 'uid' => $uid, 'area' => $address->province_name));
            if ($template->num_rows() > 0) {
                $template   = $this->filteTemplate($template);
                $orderGoods = $this->calculationFreight($orderGoods, $template, $address->province_name);
            }
        }
        return $orderGoods;
    }

    //过滤  重复的运费
    public function filteTemplate($template)
    {
        $result = array();
        foreach ($template->result() as $value){
            $result[$value->tid] = $value;
        }
        return $result;
    }

    /**
     *      * 根据运费模版 计算运费
     * 运费 1，按件算  运费 = 第一件价格 + 后面的累加
     *     2，按重量  运费 = 第一件价格 + 后面的累加的重量价格
     * @param $orderGoods
     * @param $template
     * @param $area
     * @return mixed
     */
    public function calculationFreight($orderGoods, $template, $area)
    {
        foreach ($orderGoods as $key => $value) {
            $orderGoods[$key]['totalNum'] = 0;
            $orderGoods[$key]['totalWeight'] = 0;
            $orderGoods[$key]['totalPrice'] = 0;
            
            foreach ($value['goodsInfo'] as $k => $val) {
                //计算总件数
                $orderGoods[$key]['totalNum'] += $val->goods_num;
                //计算总重量
                $orderGoods[$key]['totalWeight'] += $val->goods_num*$val->weight;
                //计算总价格
                $orderGoods[$key]['totalPrice'] += bcmul($val->goods_num,$val->shop_price,2);
            }


        }
        
        foreach ($orderGoods as $key => $value) {
            if ($value['transport_id'] > 0) {
                $sub = 0;
                $final = 0;
                foreach ($template as $t => $item) {
                    if ($key == $item->uid) {
                        
                        $freeResult = $this->tourism_freight_free->getFreeByArea($item->tid,$area); //是不是有指定优惠地区
                        $freeArray = ($freeResult->num_rows() > 0) ? $freeResult->row(0) : array(); //是不是有指定优惠地区
                        if ($item->methods == 1) { //按件计算
                            
                            if ( !empty($freeArray) && ($freeArray->free_type==1) && (bcsub($value['totalNum'],$freeArray->number)>=0)) {
                                $final += 0;// 件数优惠
                            } else if ( !empty($freeArray) && ($freeArray->free_type==2) && (bcsub($value['totalPrice'],$freeArray->money,2)>=0)) {
                                $final += 0; //  金额优惠
                            } else { 
                                if ($item->add_unit == 0 || $item->goods_num < $item->first_unit) {
                                    $final += $item->first_price;
                                } else {
                                    $goodsNum = ceil(($value['totalNum'] - $item->first_unit) / $item->add_unit); //减去第一件 除以续件的数量  得到几个续件
                                    $sub += bcmul($goodsNum, $item->add_price, 2);
                                    $final += bcadd($sub, $item->first_price, 2);
                                }
                            }
                        } 
                        
                        if ($item->methods == 2) { //按重量计算
                            
                            $weight = ($value['totalWeight']) / 1000;
                            if ( !empty($freeArray) && ($freeArray->free_type==1) && (bcsub($weight,$freeArray->number,3)>=0 )) { //如果有优惠信息
                                $final += 0; //重量优惠
                            } else if ( !empty($freeArray) && ($freeArray->free_type==2) && (bcsub($value['totalPrice'],$freeArray->money,2)>=0) ){
                                $final += 0; //金额优惠
                            } else {
                                if ($item->add_unit == 0 || $weight <= $item->first_unit) {
                                    $final += $item->first_price;
                                } else {
                                    $over_weight = ceil( ($weight - $item->first_unit)/$item->add_unit); //减去第一件重量 后面的重量  -- 请与pc端保持一致的写法
                                    $sub += bcmul($over_weight, $item->add_price, 2);
                                    $final += bcadd($sub, $item->first_price , 2);
                                }
                            }
                        }
                        
                        break;
                    }
                }
                $orderGoods[$key]['transport_cost'] = $final;
            }
        }
        return $orderGoods;
    }
    
     /*
     *创建订单
     **/
    public function submit()
    {
        $vanguard     = $this->input->post('vanguard');
        $message      = $this->input->post('message');
        $swimStatus   = $this->input->post('swim');
        $payment_type = $this->input->post('payment_type') ? $this->input->post('payment_type') : 1;
        $address_id   = $this->input->post('address_id');

        $where = $address_id ? ['address_id' => $address_id] : ['uid' => $this->uid];
        $address = $this->tourism_delivery_address->findOne($where);
        if ($address->num_rows() <= 0) {
            $this->jsonMessage('收获地址错误，刷新重新选择');
        }
        $address = $address->row();
        $detail = $this->getDelivery($address); //获取详细地址
        $tourismProfit = array();

        $mainOrderPayTotal = 0;
        $actualBonus = $swimStatus ? $this->user_account->findByUid($this->uid)->row(0)->amount_bonus : 0;// 实际有多少U币
        $order = $this->unitCost($address);
        if (empty($order)) {
            $this->jsonMessage('收获地址错误，商品失效,请从新选择商品');
        }

        //新加  产品限购 2016-01-07
        foreach ($order as $item) {
            foreach ($item['goodsInfo'] as $value) {
                //产品限购
                if ($value->limit_num > 0) {
                    // 购买数量超过 产品限量
                    if ($value->goods_num > $value->limit_num) {
                       $this->jsonMessage($value->goods_name . '（一个用户限购' . $value->limit_num . '件）');
                    }
                    if ($value->limit_day > 0) {
                       $bayNum = $this->tourism_order->findBayNum($this->uid, $value->goods_attr_id, $value->limit_day);
                       if (($bayNum + $value->goods_num) > $value->limit_num) {
                           $this->jsonMessage($value->goods_name . '（一个用户在'. $value->limit_day . '天内，限购'.$value->limit_num . '件）');
                       }
                    }
                }
            }
        }

        $this->tourismStreamInitialize();//初始化  订单分润类
        $main_order_sn = getOrderSn();

        $this->db->trans_begin();
        foreach ($order as $it => $item) {
            $order_should_subtotal = 0;//订单应支付 order_price
            $order_actual_subtotal = 0;//订单实际支付价格 actual_price
            $order_actual_swim     = 0;//订单中可以支付的U币
            
            $item['detail']        = $detail;
            $item['payer_uid']     = $this->uid;
            $item['seller_uid']    = $it;
            $item['address_id']    = $address->address_id;
            $item['order_main_sn'] = $main_order_sn;
            $item['vanguard']      = $vanguard[$it];
            $item['message']       = $message[$it];
            $item['payment_type']  = $payment_type;
            $item['user_name']     = $this->userName;
            $order_id = $this->tourism_order->insertTourismOrder($item);
            foreach ($item['goodsInfo'] as $key => $value) {
                $parameter = array(
                    'sellerUid' => $this->uid,
                    'parentUid' => $this->userParentId,
                    'bitTrade'  => $this->userType,
                    'productId' => $value->goods_attr_id,
                    'number'    => $value->goods_num,
                    'bitWan'    => $payment_type, //1:在线支付；2：到付
                    'supplyUid' => $value->uid,
                    'rateId'    => $value->rate_id, //分润模版ID
                );
                //分润 ---- start
                $profit = $this->tourismstream->tourism($parameter);
                if (empty($profit)) {
                    $this->db->trans_rollback();
                    $error = implode(',', $this->tourismstream->getError());
                    $this->jsonMessage($error);
                }
                $tourism_price = $this->tourismstream->orderPayTotal;//实际支付价格
                $value->pay_amount = bcdiv($this->tourismstream->orderPayTotal, $value->goods_num,2);//实际支付单价
                $value->calculate_method = $this->tourismstream->calculate_method;//议价分润
                $value->supply_price     = $this->tourismstream->supply_price;//供应价
                $value->shop_price       = $this->tourismstream->shop_price;//销售价
                $order_should_subtotal += bcmul($value->shop_price, $value->goods_num, 2);//实际商品总价
                if ((bcsub($actualBonus,($value->swim)*($value->goods_num),2) >= 0) && (bcsub($tourism_price,($value->swim)*($value->goods_num),2) >= 0)) { //U币可以支付的话  而且 实际支付大于U币使用量
                    $order_actual_swim += ($value->swim)*($value->goods_num);
                    $order_actual_subtotal += ($tourism_price - ($value->swim)*($value->goods_num));//实际支付商品总价
                    $actualBonus -= ($value->swim)*($value->goods_num); //多个订单购买的话，U币扣除相减
                    $value->swim = $value->swim;//每个商品可使用U币 ，那个tourism_order_product为了退款审核;
                } else { //U币不能支付的话
                    $order_actual_subtotal += $tourism_price;//实际支付商品总价
                    $value->swim = 0;// 如果商品不能支付U币，那个tourism_order_product为零，为了退款审核
                }
                $order_product_id = $this->tourism_order_product->insertTourismOrderProduct($value, $order_id);
                $goodsNum = $this->tourism_goods_attr->updateGoodsNum(array('goods_attr_id'=>$value->goods_attr_id, 'goods_num'=> -$value->goods_num));
                if (!$order_product_id || !$goodsNum) {
                    $this->db->trans_rollback();
                    $this->jsonMessage('订单生成失败,请刷新从试2');
                }
                $tourismProfit[$order_product_id] = $profit;
            }
            $orderUpdateParams[$order_id]['order_id']        = $order_id;
            $orderUpdateParams[$order_id]['order_price']     = $order_should_subtotal;
            $orderUpdateParams[$order_id]['actual_price']    = $order_actual_subtotal;
            $orderUpdateParams[$order_id]['order_pay_total'] = $order_actual_subtotal;
            $orderUpdateParams[$order_id]['pay_swim']        = $order_actual_swim;   //更新实际支付订单中实际支付多少U币
            $mainOrderPayTotal += bcadd($order_actual_subtotal, $item['transport_cost'], 2);
        }

        $update = $this->tourism_order->updateBatch($orderUpdateParams);
        $profit_is = $this->tourism_order_product_profit->insertBatch($tourismProfit);
        if (!$profit_is) {
            $this->db->trans_rollback();
            $this->jsonMessage('订单生成失败,请刷新从试3');
        }
        //插入总订单
        $main_params['order_sn']     = $main_order_sn;
        $main_params['order_amount'] = $mainOrderPayTotal;
        $main_order = $this->tourism_order_main->insertTourismOrderMain($main_params);
        $flag = $this->cleatCart();
        if (!$main_order || !$flag) {
            $this->db->trans_rollback();
            $this->jsonMessage('订单生成失败,请刷新从试4');
        }
        if ($this->db->trans_status() === true) {
            $this->session->set_userdata('last_order_sn', $main_order_sn);
            $this->db->trans_commit();
            $this->jsonMessage('',site_url('tourism/payment/payOrderLine'));
        }
    }

    //删除cookie 清除购物车
    public function cleatCart()
    {
        $goodsAttrId =  get_cookie("tid");
        $cak = get_cookie('cbk');
        $goodsAttrId = explode(',', $goodsAttrId);
        if ($cak == 1) {
            $goodsAttr = $this->tourism_cart_goods->deleteAttrId($goodsAttrId, $this->uid);
            if (!$goodsAttr) {
                return false;
            }
        }
        return true;
    }

    public function tourismStreamInitialize()
    {
        $config = array(
            'price_profit'             => 'tourism_goods_profit', //分润表
            'bargaining'               => 'tourism_goods_bargaining', //议价表
            'user'                     => 'user',              //用户表
            'tourism_goods_attr'       => 'tourism_goods_attr',   //商品价格表
            'user_related_self'        => 'user_related_self', //供应商对应分销商账户
            'provider_poundage_profit' => 'provider_poundage_profit', //供应商账号对应分销商账号利润分成
            'tourism_profit_rate'      => 'tourism_profit_rate',  //分润模版
            'user_credit'              => 'user_credit', //授信表
            'user_credit_log'          => 'user_credit_log', //授信记录表
        );
        $this->tourismstream->initialize($config);
    }

    /*
  * 创建订单地址 存储
  * */
    public function  getDelivery($address)
    {
        $delivery['receiver_name'] = $address->receiver_name;
        $delivery['province_name'] = $address->province_name;
        $delivery['detailed']      = $address->province_name.' '.$address->city_name.' '.$address->district_name.' '.$address->detailed;
        $delivery['tel']           = $address->tel;
        $delivery['code']          = $address->code;
        return json_encode($delivery);
    }
}